package com.beesoft.demo.config;

import com.beesoft.demo.entity.Country;
import com.beesoft.demo.entity.Language;
import com.beesoft.demo.repository.CountryRepository;
import com.beesoft.demo.repository.LanguageRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(
    name = "app.init-data.enabled", 
    havingValue = "true",
    matchIfMissing = true
)
public class DataInitializer implements CommandLineRunner {
    private final LanguageRepository languageRepository;
    private final CountryRepository countryRepository;

    @Override
    public void run(String... args) {
        log.info("开始初始化数据库数据...");
        initLanguages();
        initCountries();
        log.info("数据库数据初始化完成！");
    }

    private void initLanguages() {
        if (languageRepository.count() > 0) {
            log.info("语言数据已存在，跳过初始化");
            return;
        }

        log.info("正在初始化语言数据...");

        // 主要语言（parent_id 为 null）
        Language zh = createLanguage("zh", null, 
            "{\"zh\":\"中文\",\"tw\":\"中文\",\"en\":\"Chinese\",\"es\":\"Chino\",\"fr\":\"Chinois\",\"de\":\"Chinesisch\",\"it\":\"Cinese\",\"pt\":\"Chinês\",\"ru\":\"Китайский\",\"ja\":\"中国語\",\"ko\":\"중국어\"}");
        
        Language en = createLanguage("en", null,
            "{\"zh\":\"英语\",\"tw\":\"英語\",\"en\":\"English\",\"es\":\"Inglés\",\"fr\":\"Anglais\",\"de\":\"Englisch\",\"it\":\"Inglese\",\"pt\":\"Inglês\",\"ru\":\"Английский\",\"ja\":\"英語\",\"ko\":\"영어\"}");
        
        Language es = createLanguage("es", null,
            "{\"zh\":\"西班牙语\",\"tw\":\"西班牙語\",\"en\":\"Spanish\",\"es\":\"Español\",\"fr\":\"Espagnol\",\"de\":\"Spanisch\",\"it\":\"Spagnolo\",\"pt\":\"Espanhol\",\"ru\":\"Испанский\",\"ja\":\"スペイン語\",\"ko\":\"스페인어\"}");
        
        Language fr = createLanguage("fr", null,
            "{\"zh\":\"法语\",\"tw\":\"法語\",\"en\":\"French\",\"es\":\"Francés\",\"fr\":\"Français\",\"de\":\"Französisch\",\"it\":\"Francese\",\"pt\":\"Francês\",\"ru\":\"Французский\",\"ja\":\"フランス語\",\"ko\":\"프랑스어\"}");
        
        Language de = createLanguage("de", null,
            "{\"zh\":\"德语\",\"tw\":\"德語\",\"en\":\"German\",\"es\":\"Alemán\",\"fr\":\"Allemand\",\"de\":\"Deutsch\",\"it\":\"Tedesco\",\"pt\":\"Alemão\",\"ru\":\"Немецкий\",\"ja\":\"ドイツ語\",\"ko\":\"독일어\"}");
        
        Language it = createLanguage("it", null,
            "{\"zh\":\"意大利语\",\"tw\":\"意大利語\",\"en\":\"Italian\",\"es\":\"Italiano\",\"fr\":\"Italien\",\"de\":\"Italienisch\",\"it\":\"Italiano\",\"pt\":\"Italiano\",\"ru\":\"Итальянский\",\"ja\":\"イタリア語\",\"ko\":\"이탈리아어\"}");
        
        Language pt = createLanguage("pt", null,
            "{\"zh\":\"葡萄牙语\",\"tw\":\"葡萄牙語\",\"en\":\"Portuguese\",\"es\":\"Portugués\",\"fr\":\"Portugais\",\"de\":\"Portugiesisch\",\"it\":\"Portoghese\",\"pt\":\"Português\",\"ru\":\"Португальский\",\"ja\":\"ポルトガル語\",\"ko\":\"포르투갈어\"}");
        
        Language ru = createLanguage("ru", null,
            "{\"zh\":\"俄语\",\"tw\":\"俄語\",\"en\":\"Russian\",\"es\":\"Ruso\",\"fr\":\"Russe\",\"de\":\"Russisch\",\"it\":\"Russo\",\"pt\":\"Russo\",\"ru\":\"Русский\",\"ja\":\"ロシア語\",\"ko\":\"러시아어\"}");
        
        Language ja = createLanguage("ja", null,
            "{\"zh\":\"日语\",\"tw\":\"日語\",\"en\":\"Japanese\",\"es\":\"Japonés\",\"fr\":\"Japonais\",\"de\":\"Japanisch\",\"it\":\"Giapponese\",\"pt\":\"Japonês\",\"ru\":\"Японский\",\"ja\":\"日本語\",\"ko\":\"일본어\"}");
        
        Language ko = createLanguage("ko", null,
            "{\"zh\":\"韩语\",\"tw\":\"韓語\",\"en\":\"Korean\",\"es\":\"Coreano\",\"fr\":\"Coréen\",\"de\":\"Koreanisch\",\"it\":\"Coreano\",\"pt\":\"Coreano\",\"ru\":\"Корейский\",\"ja\":\"韓国語\",\"ko\":\"한국어\"}");

        // 保存主要语言并获取ID
        zh = languageRepository.save(zh);
        en = languageRepository.save(en);
        es = languageRepository.save(es);
        fr = languageRepository.save(fr);
        de = languageRepository.save(de);
        it = languageRepository.save(it);
        pt = languageRepository.save(pt);
        ru = languageRepository.save(ru);
        ja = languageRepository.save(ja);
        ko = languageRepository.save(ko);

        // 国家/地区语言变体（有 parent_id）
        createLanguage("zh-CN", zh.getId(),
            "{\"zh\":\"简体中文\",\"tw\":\"簡體中文\",\"en\":\"Simplified Chinese\",\"es\":\"Chino simplificado\",\"fr\":\"Chinois simplifié\",\"de\":\"Vereinfachtes Chinesisch\",\"it\":\"Cinese semplificato\",\"pt\":\"Chinês simplificado\",\"ru\":\"Упрощенный китайский\",\"ja\":\"簡体字中国語\",\"ko\":\"중국어 간체\"}");
        
        createLanguage("zh-TW", zh.getId(),
            "{\"zh\":\"繁体中文\",\"tw\":\"繁體中文\",\"en\":\"Traditional Chinese\",\"es\":\"Chino tradicional\",\"fr\":\"Chinois traditionnel\",\"de\":\"Traditionelles Chinesisch\",\"it\":\"Cinese tradizionale\",\"pt\":\"Chinês tradicional\",\"ru\":\"Традиционный китайский\",\"ja\":\"繁体字中国語\",\"ko\":\"중국어 번체\"}");
        
        createLanguage("zh-HK", zh.getId(),
            "{\"zh\":\"香港中文\",\"tw\":\"香港中文\",\"en\":\"Hong Kong Chinese\",\"es\":\"Chino de Hong Kong\",\"fr\":\"Chinois de Hong Kong\",\"de\":\"Hongkong-Chinesisch\",\"it\":\"Cinese di Hong Kong\",\"pt\":\"Chinês de Hong Kong\",\"ru\":\"Гонконгский китайский\",\"ja\":\"香港中国語\",\"ko\":\"홍콩 중국어\"}");
        
        createLanguage("en-US", en.getId(),
            "{\"zh\":\"美式英语\",\"tw\":\"美式英語\",\"en\":\"American English\",\"es\":\"Inglés americano\",\"fr\":\"Anglais américain\",\"de\":\"Amerikanisches Englisch\",\"it\":\"Inglese americano\",\"pt\":\"Inglês americano\",\"ru\":\"Американский английский\",\"ja\":\"アメリカ英語\",\"ko\":\"미국 영어\"}");
        
        createLanguage("en-GB", en.getId(),
            "{\"zh\":\"英式英语\",\"tw\":\"英式英語\",\"en\":\"British English\",\"es\":\"Inglés británico\",\"fr\":\"Anglais britannique\",\"de\":\"Britisches Englisch\",\"it\":\"Inglese britannico\",\"pt\":\"Inglês britânico\",\"ru\":\"Британский английский\",\"ja\":\"イギリス英語\",\"ko\":\"영국 영어\"}");
        
        createLanguage("es-ES", es.getId(),
            "{\"zh\":\"西班牙西班牙语\",\"tw\":\"西班牙西班牙語\",\"en\":\"European Spanish\",\"es\":\"Español de España\",\"fr\":\"Espagnol d'Espagne\",\"de\":\"Europäisches Spanisch\",\"it\":\"Spagnolo europeo\",\"pt\":\"Espanhol europeu\",\"ru\":\"Европейский испанский\",\"ja\":\"ヨーロッパスペイン語\",\"ko\":\"유럽 스페인어\"}");
        
        createLanguage("es-MX", es.getId(),
            "{\"zh\":\"墨西哥西班牙语\",\"tw\":\"墨西哥西班牙語\",\"en\":\"Mexican Spanish\",\"es\":\"Español mexicano\",\"fr\":\"Espagnol mexicain\",\"de\":\"Mexikanisches Spanisch\",\"it\":\"Spagnolo messicano\",\"pt\":\"Espanhol mexicano\",\"ru\":\"Мексиканский испанский\",\"ja\":\"メキシコスペイン語\",\"ko\":\"멕시코 스페인어\"}");
        
        createLanguage("pt-BR", pt.getId(),
            "{\"zh\":\"巴西葡萄牙语\",\"tw\":\"巴西葡萄牙語\",\"en\":\"Brazilian Portuguese\",\"es\":\"Portugués brasileño\",\"fr\":\"Portugais brésilien\",\"de\":\"Brasilianisches Portugiesisch\",\"it\":\"Portoghese brasiliano\",\"pt\":\"Português brasileiro\",\"ru\":\"Бразильский португальский\",\"ja\":\"ブラジルポルトガル語\",\"ko\":\"브라질 포르투갈어\"}");
        
        createLanguage("pt-PT", pt.getId(),
            "{\"zh\":\"欧洲葡萄牙语\",\"tw\":\"歐洲葡萄牙語\",\"en\":\"European Portuguese\",\"es\":\"Portugués europeo\",\"fr\":\"Portugais européen\",\"de\":\"Europäisches Portugiesisch\",\"it\":\"Portoghese europeo\",\"pt\":\"Português europeu\",\"ru\":\"Европейский португальский\",\"ja\":\"ヨーロッパポルトガル語\",\"ko\":\"유럽 포르투갈어\"}");

        languageRepository.flush();
        log.info("语言数据初始化完成，共 {} 条记录", languageRepository.count());
    }
    private void initCountries() {
        if (countryRepository.count() > 0) {
            log.info("国家数据已存在，跳过初始化");
            return;
        }

        log.info("正在初始化国家数据...");

        // 主要国家数据
        createCountry("CN", 
            "{\"zh\":\"中国\",\"tw\":\"中國\",\"en\":\"China\",\"es\":\"China\",\"fr\":\"Chine\",\"de\":\"China\",\"it\":\"Cina\",\"pt\":\"China\",\"ru\":\"Китай\",\"ja\":\"中国\",\"ko\":\"중국\"}");
        
        createCountry("US", 
            "{\"zh\":\"美国\",\"tw\":\"美國\",\"en\":\"United States\",\"es\":\"Estados Unidos\",\"fr\":\"États-Unis\",\"de\":\"Vereinigte Staaten\",\"it\":\"Stati Uniti\",\"pt\":\"Estados Unidos\",\"ru\":\"Соединенные Штаты\",\"ja\":\"アメリカ合衆国\",\"ko\":\"미국\"}");
        
        createCountry("GB", 
            "{\"zh\":\"英国\",\"tw\":\"英國\",\"en\":\"United Kingdom\",\"es\":\"Reino Unido\",\"fr\":\"Royaume-Uni\",\"de\":\"Vereinigtes Königreich\",\"it\":\"Regno Unito\",\"pt\":\"Reino Unido\",\"ru\":\"Великобритания\",\"ja\":\"イギリス\",\"ko\":\"영국\"}");
        
        createCountry("JP", 
            "{\"zh\":\"日本\",\"tw\":\"日本\",\"en\":\"Japan\",\"es\":\"Japón\",\"fr\":\"Japon\",\"de\":\"Japan\",\"it\":\"Giappone\",\"pt\":\"Japão\",\"ru\":\"Япония\",\"ja\":\"日本\",\"ko\":\"일본\"}");
        
        createCountry("KR", 
            "{\"zh\":\"韩国\",\"tw\":\"韓國\",\"en\":\"South Korea\",\"es\":\"Corea del Sur\",\"fr\":\"Corée du Sud\",\"de\":\"Südkorea\",\"it\":\"Corea del Sud\",\"pt\":\"Coreia do Sul\",\"ru\":\"Южная Корея\",\"ja\":\"韓国\",\"ko\":\"대한민국\"}");
        
        createCountry("FR", 
            "{\"zh\":\"法国\",\"tw\":\"法國\",\"en\":\"France\",\"es\":\"Francia\",\"fr\":\"France\",\"de\":\"Frankreich\",\"it\":\"Francia\",\"pt\":\"França\",\"ru\":\"Франция\",\"ja\":\"フランス\",\"ko\":\"프랑스\"}");
        
        createCountry("DE", 
            "{\"zh\":\"德国\",\"tw\":\"德國\",\"en\":\"Germany\",\"es\":\"Alemania\",\"fr\":\"Allemagne\",\"de\":\"Deutschland\",\"it\":\"Germania\",\"pt\":\"Alemanha\",\"ru\":\"Германия\",\"ja\":\"ドイツ\",\"ko\":\"독일\"}");
        
        createCountry("IT", 
            "{\"zh\":\"意大利\",\"tw\":\"意大利\",\"en\":\"Italy\",\"es\":\"Italia\",\"fr\":\"Italie\",\"de\":\"Italien\",\"it\":\"Italia\",\"pt\":\"Itália\",\"ru\":\"Италия\",\"ja\":\"イタリア\",\"ko\":\"이탈리아\"}");
        
        createCountry("ES", 
            "{\"zh\":\"西班牙\",\"tw\":\"西班牙\",\"en\":\"Spain\",\"es\":\"España\",\"fr\":\"Espagne\",\"de\":\"Spanien\",\"it\":\"Spagna\",\"pt\":\"Espanha\",\"ru\":\"Испания\",\"ja\":\"スペイン\",\"ko\":\"스페인\"}");
        
        createCountry("MX", 
            "{\"zh\":\"墨西哥\",\"tw\":\"墨西哥\",\"en\":\"Mexico\",\"es\":\"México\",\"fr\":\"Mexique\",\"de\":\"Mexiko\",\"it\":\"Messico\",\"pt\":\"México\",\"ru\":\"Мексика\",\"ja\":\"メキシコ\",\"ko\":\"멕시코\"}");
        
        createCountry("BR", 
            "{\"zh\":\"巴西\",\"tw\":\"巴西\",\"en\":\"Brazil\",\"es\":\"Brasil\",\"fr\":\"Brésil\",\"de\":\"Brasilien\",\"it\":\"Brasile\",\"pt\":\"Brasil\",\"ru\":\"Бразилия\",\"ja\":\"ブラジル\",\"ko\":\"브라질\"}");
        
        createCountry("PT", 
            "{\"zh\":\"葡萄牙\",\"tw\":\"葡萄牙\",\"en\":\"Portugal\",\"es\":\"Portugal\",\"fr\":\"Portugal\",\"de\":\"Portugal\",\"it\":\"Portogallo\",\"pt\":\"Portugal\",\"ru\":\"Португалия\",\"ja\":\"ポルトガル\",\"ko\":\"포르투갈\"}");
        
        createCountry("RU", 
            "{\"zh\":\"俄罗斯\",\"tw\":\"俄羅斯\",\"en\":\"Russia\",\"es\":\"Rusia\",\"fr\":\"Russie\",\"de\":\"Russland\",\"it\":\"Russia\",\"pt\":\"Rússia\",\"ru\":\"Россия\",\"ja\":\"ロシア\",\"ko\":\"러시아\"}");
        
        createCountry("CA", 
            "{\"zh\":\"加拿大\",\"tw\":\"加拿大\",\"en\":\"Canada\",\"es\":\"Canadá\",\"fr\":\"Canada\",\"de\":\"Kanada\",\"it\":\"Canada\",\"pt\":\"Canadá\",\"ru\":\"Канада\",\"ja\":\"カナダ\",\"ko\":\"캐나다\"}");
        
        createCountry("AU", 
            "{\"zh\":\"澳大利亚\",\"tw\":\"澳大利亞\",\"en\":\"Australia\",\"es\":\"Australia\",\"fr\":\"Australie\",\"de\":\"Australien\",\"it\":\"Australia\",\"pt\":\"Austrália\",\"ru\":\"Австралия\",\"ja\":\"オーストラリア\",\"ko\":\"호주\"}");
        
        createCountry("IN", 
            "{\"zh\":\"印度\",\"tw\":\"印度\",\"en\":\"India\",\"es\":\"India\",\"fr\":\"Inde\",\"de\":\"Indien\",\"it\":\"India\",\"pt\":\"Índia\",\"ru\":\"Индия\",\"ja\":\"インド\",\"ko\":\"인도\"}");
        
        createCountry("TW", 
            "{\"zh\":\"中国台湾\",\"tw\":\"中國台灣\",\"en\":\"Taiwan\",\"es\":\"Taiwán\",\"fr\":\"Taïwan\",\"de\":\"Taiwan\",\"it\":\"Taiwan\",\"pt\":\"Taiwan\",\"ru\":\"Тайвань\",\"ja\":\"台湾\",\"ko\":\"대만\"}");
        
        createCountry("HK", 
            "{\"zh\":\"中国香港\",\"tw\":\"中國香港\",\"en\":\"Hong Kong\",\"es\":\"Hong Kong\",\"fr\":\"Hong Kong\",\"de\":\"Hongkong\",\"it\":\"Hong Kong\",\"pt\":\"Hong Kong\",\"ru\":\"Гонконг\",\"ja\":\"香港\",\"ko\":\"홍콩\"}");
        
        createCountry("SG", 
            "{\"zh\":\"新加坡\",\"tw\":\"新加坡\",\"en\":\"Singapore\",\"es\":\"Singapur\",\"fr\":\"Singapour\",\"de\":\"Singapur\",\"it\":\"Singapore\",\"pt\":\"Singapura\",\"ru\":\"Сингапур\",\"ja\":\"シンガポール\",\"ko\":\"싱가포르\"}");
        
        createCountry("NL", 
            "{\"zh\":\"荷兰\",\"tw\":\"荷蘭\",\"en\":\"Netherlands\",\"es\":\"Países Bajos\",\"fr\":\"Pays-Bas\",\"de\":\"Niederlande\",\"it\":\"Paesi Bassi\",\"pt\":\"Países Baixos\",\"ru\":\"Нидерланды\",\"ja\":\"オランダ\",\"ko\":\"네덜란드\"}");

        countryRepository.flush();
        log.info("国家数据初始化完成，共 {} 条记录", countryRepository.count());
    }

    private Language createLanguage(String code, Long parentId, String title) {
        Language language = new Language();
        language.setCode(code);
        language.setParentId(parentId);
        language.setTitle(title);
        return languageRepository.save(language);
    }
    private Country createCountry(String code, String title) {
        Country country = new Country();
        country.setCode(code);
        country.setTitle(title);
        return countryRepository.save(country);
    }
}
